package com.channel.temperature.collect.ui.fragment

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.Legend.LegendForm
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.components.YAxis.AxisDependency
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.ColorTemplate
import com.gyf.immersionbar.ktx.immersionBar
import com.channel.temperature.collect.app.base.BaseFragment
import com.channel.temperature.collect.app.widget.MyMarkerView
import com.channel.temperature.collect.databinding.FragmentOfflineBinding
import com.channel.temperature.collect.ui.viewmodel.OfflineCollectModel
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.MvvmHelper
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat


class OfflineCollectFragment : BaseFragment<OfflineCollectModel, FragmentOfflineBinding>(),
    OnChartValueSelectedListener {
    protected var tfLight: Typeface? = null

    companion object {
        fun newInstance(): OfflineCollectFragment {
            val args = Bundle()
            val fragment = OfflineCollectFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        tfLight = Typeface.createFromAsset(
            MvvmHelper.app.applicationContext.assets, "OpenSans-Light.ttf"
        );

        mBind.chart.setOnChartValueSelectedListener(this)

        // create marker to display box when values are selected
        val mv = MyMarkerView(
            MvvmHelper.app.applicationContext,
            com.channel.temperature.collect.R.layout.custom_marker_view
        )

        // Set the marker to the chart

        // Set the marker to the chart
        mv.setChartView(mBind.chart)
        mBind.chart.setMarker(mv)

        mBind.chart.description.isEnabled = false;
        mBind.chart.setTouchEnabled(true)
        mBind.chart.dragDecelerationFrictionCoef = 0.9f
        mBind.chart.setDragEnabled(true);
        mBind.chart.setScaleEnabled(true);
        mBind.chart.setDrawGridBackground(false);
        mBind.chart.setHighlightPerDragEnabled(true);
        mBind.chart.setPinchZoom(false);
        mBind.chart.setBackgroundColor(Color.LTGRAY);


        // get the legend (only possible after setting data)
        // get the legend (only possible after setting data)
        val l: Legend = mBind.chart.getLegend()

        // modify the legend ...

        // modify the legend ...
        l.form = LegendForm.LINE
        l.typeface = tfLight
        l.textSize = 11f
        l.textColor = Color.WHITE
        l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)
//        l.setYOffset(11f);

        //        l.setYOffset(11f);
        val xAxis: XAxis = mBind.chart.getXAxis()
        xAxis.typeface = tfLight
        xAxis.textSize = 11f
        xAxis.textColor = Color.WHITE
        xAxis.setDrawGridLines(false)
        xAxis.setDrawAxisLine(false)

        val leftAxis: YAxis = mBind.chart.getAxisLeft()
        leftAxis.typeface = tfLight
        leftAxis.textColor = ColorTemplate.getHoloBlue()
        leftAxis.axisMaximum = 200f
        leftAxis.axisMinimum = 0f
        leftAxis.setDrawGridLines(false)
        leftAxis.isGranularityEnabled = true

        val rightAxis: YAxis = mBind.chart.getAxisRight()
        rightAxis.typeface = tfLight
        rightAxis.textColor = Color.RED
        rightAxis.axisMaximum = 900f
        rightAxis.axisMinimum = -200f
        rightAxis.setDrawGridLines(false)
        rightAxis.setDrawZeroLine(false)
        rightAxis.isGranularityEnabled = false
    }

    /**
     * 懒加载 第一次获取视图的时候 触发
     */
    override fun lazyLoadData() {

    }

    override fun onRequestSuccess() {


    }

    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mBind.queryTasks
        ) {
            when (it) {
                mBind.queryTasks -> {
                    lifecycleScope.launch {
//                        mViewModel.setLineData()
                    }

                }

            }
        }
    }

    private fun setData(count: Int, range: Float) {
        val values1 = ArrayList<Entry>()
        for (i in 0 until count) {
            val `val` = (Math.random() * (range / 2f)).toFloat() + 50
            values1.add(Entry(i.toFloat(), `val`))
        }
        val values2 = ArrayList<Entry>()
        for (i in 0 until count) {
            val `val` = (Math.random() * range).toFloat() + 450
            values2.add(Entry(i.toFloat(), `val`))
        }
//        val values3 = ArrayList<Entry>()
//        for (i in 0 until count) {
//            val `val` = (Math.random() * range).toFloat() + 500
//            values3.add(Entry(i.toFloat(), `val`))
//        }
        val set1: LineDataSet
        val set2: LineDataSet
        if (mBind.chart.getData() != null &&
            mBind.chart.getData().getDataSetCount() > 0
        ) {
            set1 = mBind.chart.getData().getDataSetByIndex(0) as LineDataSet
            set2 = mBind.chart.getData().getDataSetByIndex(1) as LineDataSet
            set1.values = values1
            set2.values = values2
            mBind.chart.getData().notifyDataChanged()
            mBind.chart.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(values1, "温度")
            set1.axisDependency = AxisDependency.LEFT
            set1.color = ColorTemplate.getHoloBlue()
            set1.setCircleColor(Color.WHITE)
            set1.lineWidth = 2f
            set1.circleRadius = 3f
            set1.fillAlpha = 65
            set1.fillColor = ColorTemplate.getHoloBlue()
            set1.highLightColor = Color.rgb(244, 117, 117)
            set1.setDrawCircleHole(false)
            set1.setDrawCircles(false)
            set1.setDrawValues(false)
            //set1.setFillFormatter(new MyFillFormatter(0f));
            //set1.setDrawHorizontalHighlightIndicator(false);
            //set1.setVisible(false);
            //set1.setCircleHoleColor(Color.WHITE);

            // create a dataset and give it a type
            set2 = LineDataSet(values2, "压力")
            set2.axisDependency = AxisDependency.RIGHT
            set2.color = Color.RED
            set2.setCircleColor(Color.WHITE)
            set2.lineWidth = 2f
            set2.circleRadius = 3f
            set2.fillAlpha = 65
            set2.fillColor = Color.RED
            set2.setDrawCircleHole(false)
            set2.setDrawCircles(false)
            set2.setDrawValues(false)
            set2.highLightColor = Color.rgb(244, 117, 117)
            //set2.setFillFormatter(new MyFillFormatter(900f));

            // create a data object with the data sets
            val data = LineData(set1, set2)
            data.setValueTextColor(Color.WHITE)
            data.setValueTextSize(9f)

            // set data
            mBind.chart.setData(data)
        }
    }


    override fun onValueSelected(e: Entry?, h: Highlight?) {
        e?.let {
            mBind.chart.centerViewToAnimated(
                it.x, e.y, h?.let { it1 ->
                    mBind.chart.data.getDataSetByIndex(it1.dataSetIndex)
                        .axisDependency
                }, 500
            )
        };
    }

    override fun onNothingSelected() {
    }

    override fun onResume() {
        super.onResume()
        Log.e("onResume", "离线收集")
        immersionBar {
            titleBar(mBind.customToolbar)
        }
    }

}